package com.xdja.netty.handler.inbound;

import com.xdja.netty.conf.HttpManager;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * description
 *
 * @author zk
 * @since 2018/7/23
 */
public class HttpMappingDecoder extends MessageToMessageDecoder<HttpManager.Entry<HttpRequest, HttpContent>> {

    @Override
    protected void decode(ChannelHandlerContext ctx, HttpManager.Entry<HttpRequest, HttpContent> msg, List<Object> out) throws Exception {
        HttpManager.addMapping(getMappingUrl(msg), msg);

        HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.wrappedBuffer("your add is ok".getBytes()));
        httpResponse.headers().set("transfer-encoding", "trunked");
        httpResponse.headers().set("content-type", "text/plain;charset=utf-8");
        ctx.channel().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * 获取http实体中真实的url
     *
     * @param msg http msg
     * @return real url
     */
    private String getMappingUrl(HttpManager.Entry<HttpRequest, HttpContent> msg) {
        AtomicReference<String> result = new AtomicReference<>();
        QueryStringDecoder decoder = new QueryStringDecoder(msg.getHttpRequest().uri());
        decoder.parameters().entrySet().forEach(entry -> {
            if("url".equals(entry.getKey()))
                result.set(entry.getValue().get(0));
        });
        return result.get();
    }
}
